#import "CallUserViewController.h"
#import "UIImage+ImageEffect.h"
#import "XYTransitionProtocol.h"
#import "LiveRoomViewUIControllerViewController.h"
@interface CallUserViewController ()<LiveRoomVCDelegate>
@end
@implementation CallUserViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self playAudio];
    KGlobalVariable.CallState = @"1";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callConnect:) name:KOnCallConnecting object:nil];
}
-(void)createUI
{
    self.view.backgroundColor = [UIColor blackColor];
    _bgview = [[UIImageView alloc] init];
    _bgview.contentMode = UIViewContentModeScaleAspectFill;
    _headerImage = [[UIImageView alloc] init];
    _headerImage.contentMode = UIViewContentModeScaleAspectFill;
    _nickname = [[UILabel alloc] init];
    _nickname.textColor = [UIColor whiteColor];
    _nickname.font = DEFAULT_FONT(14);
    _callStatus = [[UILabel alloc] init];
    if(_iscall == YES)
    {
        [_bgview sd_setImageWithURL:[cyurl safeUrl:_usermodel.avatar] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            _bgview.image = [image imageByBlurSoft];
        }];
        [_headerImage sd_setImageWithURL:[cyurl safeUrl:_usermodel.avatar] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        }];
        _nickname.text = _usermodel.user_nickname;
        _callStatus.text = [NSString stringWithFormat:ASLocalizedString(@"正在呼叫%@"),_usermodel.user_nickname];
    }
    else
    {
        [_bgview sd_setImageWithURL:[cyurl safeUrl:self.msessage.sender.avatar] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            _bgview.image = [image imageByBlurSoft];
        }];
        [_headerImage sd_setImageWithURL:[cyurl safeUrl:self.msessage.sender.avatar] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        }];
        _nickname.text = self.msessage.sender.user_nickname;
        _callStatus.text = [NSString stringWithFormat:ASLocalizedString(@"%@邀请与您通话"),self.msessage.sender.user_nickname];
    }
    _callStatus.textColor = [UIColor whiteColor];
    _callStatus.font = DEFAULT_FONT(12);
    _acceptButton = [[UIButton alloc] init];
    [_acceptButton setImage:IMAGE_NAMED(@"home_alert_accept") forState:UIControlStateNormal];
    _refuseButton = [[UIButton alloc] init];
    [_refuseButton setImage:IMAGE_NAMED(@"home_alert_refuse") forState:UIControlStateNormal];
    [_refuseButton addTarget:self action:@selector(handlerefuseEvent) forControlEvents:UIControlEventTouchUpInside];
    [_acceptButton addTarget:self action:@selector(handlereAcceptEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_bgview];
    [self.view addSubview:_headerImage];
    [self.view addSubview:_nickname];
    [self.view addSubview:_callStatus];
    [self.view addSubview:_acceptButton];
    [self.view addSubview:_refuseButton];
    [self setLayout];
}
-(void)CallEndCloseView
{
    [self closeView];
}
-(void)setLayout
{
    [_bgview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    [_headerImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.and.height.equalTo(@60);
        make.top.and.left.equalTo(@10);
    }];
    ViewRadius(_headerImage, 30);
    [_nickname mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_headerImage.mas_right).offset(5);
        make.top.equalTo(_headerImage).offset(5);
    }];
    [_callStatus mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_nickname);
        make.top.equalTo(_nickname.mas_bottom).offset(5);
    }];
    if(_iscall)
    {
        _acceptButton.hidden = YES;
        [_refuseButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.bottom.equalTo(self.view).offset(-80);
            make.width.height.equalTo(@90);
        }];
    }
    else
    {
        [_refuseButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.equalTo(@90);
            make.bottom.equalTo(self.view).offset(-80);
            make.centerX.equalTo(self.view).offset(-80);
        }];
        [_acceptButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view).offset(-80);
            make.centerX.equalTo(self.view).offset(80);
            make.width.and.height.equalTo(@90);
        }];
    }
}
-(void)sendCallMessage
{
    TIMConversation * group_conversation = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:_usermodel.id];
    TIMTextElem * text_elem = [[TIMTextElem alloc] init];
    [text_elem setText:@"call"];
    TIMMessage * msg = [[TIMMessage alloc] init];
    [msg addElem:text_elem];
    [group_conversation sendMessage:msg succ:^{
    } fail:^(int code, NSString *msg) {
        [MBProgressHUD showTopTipMessage:[NSString stringWithFormat:@"%@ code:%d",msg,code]];
    }];
}
-(void)playAudio
{
    NSURL *fileURL = [[NSBundle mainBundle]URLForResource:@"avchat_ring" withExtension:@".mp3"];
    NSError *aError;
    self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:&aError];
    NSString *msg = [NSString stringWithFormat:ASLocalizedString(@"音频文件声道数:%ld\n 音频文件持续时间:%g"),self.audioPlayer.numberOfChannels,self.audioPlayer.duration];
    NSLog(@"%@",msg);
    self.audioPlayer.numberOfLoops = -1;
    [self.audioPlayer prepareToPlay];
    [self.audioPlayer play];
}
- (void)viewWillAppear:(BOOL)animated {
    self.isHidenNaviBar = YES;
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self removeNotif];
    [self.audioPlayer stop];
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)removeNotif {
    [[NSNotificationCenter defaultCenter] removeObserver:KOnCallConnecting name:nil object:self];
    [[NSNotificationCenter defaultCenter] removeObserver:KOnGiftMessage name:nil object:self];
}
-(void)handlereAcceptEvent
{
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"video_call_api" A:@"reply_video_call"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.msessage.sender.id forKey:@"id"];
    [param setObject:self.msessage.sender.id forKey:@"to_user_id"];
    [param setObject:self.msessage.channel forKey:@"channel"];
    [param setObject:@"1" forKey:@"type"];
    [[HUDHelper sharedInstance] syncLoading];
    [CYNET POST:url parameters:param responseCache:^(id responseObject) {
    } success:^(id responseObject) {
        [[HUDHelper sharedInstance] syncStopLoading];
        LiveRoomViewUIControllerViewController *liveVC = [LiveRoomViewUIControllerViewController new];
        if(_iscall)
        {
            liveVC.roomName = self.channel;
            liveVC.uid = _usermodel.id;
            liveVC.isCall = self.iscall;
        }
        else
        {
            liveVC.roomName = self.msessage.channel;
            liveVC.uid = self.msessage.sender.id;
            liveVC.isCall = self.iscall;
        }
        liveVC.videoProfile = AgoraVideoProfileLandscape720P;
        liveVC.clientRole = AgoraClientRoleBroadcaster;
        liveVC.delegate = self;
        NSLog(ASLocalizedString(@"要push啊"));
        [self.navigationController pushViewController:liveVC animated:NO];
    } failure:^(NSString *error) {
        [[HUDHelper sharedInstance] syncStopLoading];
    } hasCache:NO];
}
-(void)hangUPVideoCall
{
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"video_call_api" A:@"hang_up_video_call"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [CYNET POST:url parameters:param responseCache:^(id responseObject) {
    } success:^(id responseObject) {
        [self closeView];
        [[HUDHelper sharedInstance] tipMessage:ASLocalizedString(@"通话已取消")];
    } failure:^(NSString *error) {
        [self closeView];
    } hasCache:NO];
}
-(void)handlerefuseEvent
{
    if(_iscall)
    {
        [self hangUPVideoCall];
    }
    else
    {
        NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"video_call_api" A:@"reply_video_call"];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setObject:self.msessage.sender.id forKey:@"id"];
        [param setObject:self.msessage.sender.id forKey:@"to_user_id"];
        [param setObject:self.msessage.channel forKey:@"channel"];
        [param setObject:@"2" forKey:@"type"];
        [[HUDHelper sharedInstance] syncLoading];
        [CYNET POST:url parameters:param responseCache:^(id responseObject) {
        } success:^(id responseObject) {
            [[HUDHelper sharedInstance] syncStopLoading];
            [self closeView];
            [[HUDHelper sharedInstance] tipMessage:ASLocalizedString(@"已拒绝该通话")];
        } failure:^(NSString *error) {
            [[HUDHelper sharedInstance] syncStopLoading];
            [self closeView];
        } hasCache:NO];
    }
}
- (void)callConnect:(NSNotification *)notification{
    NSLog(ASLocalizedString(@"通话机建立%@"),curUser.id);
    VMsgMessage *data = [notification.userInfo valueForKey:@"data"];
    if(!_iscall)
    {
        if(data.reply_type == 1)
        {
            [self closeView];
        }
        else
        {
            LiveRoomViewUIControllerViewController *liveVC = [LiveRoomViewUIControllerViewController new];
            liveVC.isCall = self.iscall;
            liveVC.roomName = data.channel;
            liveVC.uid = data.sender.id;
            liveVC.videoProfile = AgoraVideoProfileLandscape720P;
            liveVC.clientRole = AgoraClientRoleBroadcaster;
            liveVC.delegate = self;
            NSLog(ASLocalizedString(@"要push啊啊啊"));
            [self.navigationController pushViewController:liveVC animated:NO];
        }
    }
    else
    {
        if(data.reply_type == 2)
        {
            [self closeView];
        }
        else
        {
            LiveRoomViewUIControllerViewController *liveVC = [LiveRoomViewUIControllerViewController new];
            liveVC.isCall = self.iscall;
            liveVC.roomName = data.channel;
            liveVC.uid = data.sender.id;
            liveVC.videoProfile = AgoraVideoProfileLandscape720P;
            liveVC.clientRole = AgoraClientRoleBroadcaster;
            liveVC.delegate = self;
            [self.navigationController pushViewController:liveVC animated:NO];
        }
    }
    NSLog(ASLocalizedString(@"---接收到通知（通话）---"));
}
#pragma mark - 视频代理回调
-(void)liveVCNeedClose:(LiveRoomViewUIControllerViewController *)liveVC
{
    [liveVC.navigationController popViewControllerAnimated:NO];
    if(!_iscall)
    {
        NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"video_call_api" A:@"end_video_call"];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setObject:self.msessage.sender.id forKey:@"id"];
        [param setObject:self.msessage.sender.id forKey:@"to_user_id"];
        [param setObject:self.msessage.channel forKey:@"channel"];
        [param setObject:@"2" forKey:@"type"];
        [[HUDHelper sharedInstance] syncLoading];
        [CYNET POST:url parameters:param responseCache:^(id responseObject) {
        } success:^(id responseObject) {
            [[HUDHelper sharedInstance] syncStopLoading];
            [[HUDHelper sharedInstance] tipMessage:ASLocalizedString(@"通话已结束（被叫）")];
        } failure:^(NSString *error) {
            [[HUDHelper sharedInstance] syncStopLoading];
        } hasCache:NO];
        [self CallEndCloseView];
    }
    else
    {
        [[HUDHelper sharedInstance] syncLoading];
        NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"video_call_api" A:@"hang_up_video_call"];
        NSString *url2 = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"video_call_api" A:@"end_video_call"];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setObject:self.usermodel.id forKey:@"id"];
        [param setObject:self.usermodel.id  forKey:@"to_user_id"];
        [param setObject:self.channel forKey:@"channel"];
        [param setObject:@"2" forKey:@"type"];
        [[HUDHelper sharedInstance] syncLoading];
        [CYNET POST:url2 parameters:param responseCache:^(id responseObject) {
        } success:^(id responseObject) {
            [[HUDHelper sharedInstance] syncStopLoading];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            });
            [CYNET POST:url parameters:param responseCache:^(id responseObject) {
            } success:^(id responseObject) {
                [[HUDHelper sharedInstance] syncStopLoading];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                });
            } failure:^(NSString *error) {
                [[HUDHelper sharedInstance] syncStopLoading];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                });
            } hasCache:NO];
            [[HUDHelper sharedInstance] tipMessage:ASLocalizedString(@"通话已结束(主叫)")];
        } failure:^(NSString *error) {
            [[HUDHelper sharedInstance] syncStopLoading];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            });
        } hasCache:NO];
        [[HUDHelper sharedInstance] tipMessage:ASLocalizedString(@"通话已结束(主叫)")];
        [self CallEndCloseView];
    }
}
-(void)closeView
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.qmui_isPresented)
        {
            [self dismissViewControllerAnimated:NO completion:nil];
        }
        else
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
    });
}
- (BOOL)prefersStatusBarHidden {
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
#pragma mark ————— 转场动画起始View —————
-(UIView *)targetTransitionView{
    return self.view;
}
-(BOOL)isNeedTransition{
    return YES;
}
@end
